/* 要求手动实现数组元素分块 */
// https://leetcode.cn/problems/chunk-array/solutions/2506898/javascriptshu-zu-fen-kuai-jiao-cheng-by-la1fz/

/* 主要是api的使用，如 reduce(),Array.from(),slice() */

// 这常用于分页操作
// ##分页示例
function paginateArray (dataArr, pageSize, pageNumber) {
  // 计算当前页起始索引
  const startIndex = pageSize * (pageNumber - 1);  /* 并未处理页码为零的情况 */

  // 创建数组块
  const chunkArray = dataArr.slice(startIndex, startIndex + pageSize);

  return chunkArray;
}

// ##一：暴力 o(n) o(n)
let chunk1 = function(arr, size) {
  let chunkArray = [];
  let index = 0;

  while (index < arr.length) {
    let count = size;
    const temp = [];

    while (count-- > 0 && index < arr.length) {
      temp.push(arr[ index ]);
      index++;
    }

    chunkArray.push(temp);
  }

  return chunkArray;
};

// ##二：切片 slice() o(n) 0(1)
let chunk2 = function(arr, size) {
  const chunkArray = [];
  let index = 0;

  while (index < arr.length) {
    chunkArray.push(arr.slice(index, size));
    index += size;
  }

  return chunkArray;
};

// ##三：reduce on o1

let chunk3 = function(arr, size) {
  return arr.reduce((chunkArray, element) => {
    const lastChunk = chunkArray[ chunkArray.length - 1 ];
    if (!lastChunk || lastChunk.length === size) {
      chunkArray.push([ element ]);
    } else {
      lastChunk.push(element);
    }
    return chunkArray;
  }, []);
};

// ##四：push on on

let chunk4 = function(arr, size) {
  const result = [];
  let chunkArray = [];

  for (const element of arr) {
    if (chunkArray.length === size) {
      result.push(chunkArray);
      chunkArray = [];
    }
    chunkArray.push(element);
  }

  if (chunkArray.length !== 0) {
    result.push(chunkArray);
  }

  return result;
};

// ##五：celing on o1

let chunk5 = function(arr, size) {
  return Array.from({ length: Math.ceil(arr.length / size) }, function(_, index) {
    return arr.slice(index * size, index * size + size);
  });
};

